// 设置班级
function setClassList () {
  AjaxRequest({
    url: '/school/class_list/',
    succFun: function (res) {

      var html='<option value="0"   selected>请选择班级</option>'
      res.data.forEach(d=>{
        html+=`<option value="${d.school_class_id}"   selected>${d.class_name}</option>`
      })
      $('[name="school_class_id"]').html(html)
      if(res.data.length===0){
        layer.confirm('您暂未添加班级，请先添加班级再查看课程。', {
          title:'友情提示',
          btn: ['确定','取消'] //按钮
        }, function(){
            location.href='class_update_or_add.html'
        }, function(){

        });
      }
    }
  })
}

let dataWeekList = null
let tipsContent=$('.tips_content')
// 根据班级搜索周
$('#searchBtn').click(function (e) {
  e.preventDefault()
  var classId=$('[name="school_class_id"]').val()
  if(classId==0){
    $('#weekContent').html(tipsContent)
    layer.msg('查看课程请先选择班级',{icon:7})
    return false
  }
  getData(classId)
})
// 体验课程请求
let getUrl='/admin/experience/'
if($('#testCourse').length>0){
  getData()
}else if($('#classCourse').length>0){
  setClassList()
  getUrl='/school/curriculum/'
}
function getData(classId){
  var loading = layer.load(2); //换了种风格
  $('#weekContent').removeClass('am-u-md-7 ').addClass('am-u-md-12 ')
  $('.week_detail').hide().removeClass('animate__fadeInRight')
  AjaxRequest({
    url:getUrl,
    data: {school_class_id: classId||''},
    succFun: function (res) {
      dataWeekList = res.data.list
      $('#weakItem').html(res.data.last_name)
      var html = ''
      for (var key in dataWeekList) {
        var infoList = ''
        dataWeekList[key].forEach(function (item) {
          infoList += `<p>${item.title}</p>`
        })
        html += `
        <div class="am-u-sm-6 am-u-md-3 week_item" data-key="${key}">
            <h3 class="week_title">第${key}周</h3>
            <div class="info_list">${infoList}</div>
        </div>
        `
      }
      $('#weekContent').html(html)
      layer.close(loading)
    }
  })
}

function starFun (num) {
  var html = ''
  for (var i = 0; i < num; i++) {
    html += '<i class="am-icon-star"></i>'
  }
  return '<p class="star_content">' + html + '</p>'
}
//切换按钮
$('.switch_bar').on('click', 'span', function (e) {
  e.preventDefault()
  $(this).addClass('cur').siblings('span').removeClass('cur')
  var info = $(this).attr('data-info')
  var value = $(this).attr('data-value')
  showContentFun(info, value)
})
//点击周期
let weekIndex=0
$('.week_content').on('click', '.week_item', function () {
  weekIndex=$(this).index();
  $('#weekContent').removeClass('am-u-md-12').addClass('am-u-md-7')
  $('.week_detail').removeClass('animate__fadeInRight').show().addClass('animate__fadeInRight')
  $(this).addClass('cur').siblings('.week_item').removeClass('cur')
  var weekKey = $(this).attr('data-key')
  var weekOpt = dataWeekList[weekKey]
  var weekHtml = ''
  weekOpt.forEach(function (item, i) {
    weekHtml += `  <tr>
                        <td>${item.title}</td>
                        <td>${item.level}</td>
                        <td>${item.difficulty}</td>
                        <td>${item.duration}</td>
                        <td>${item.people_num}</td>
                        <td>
                            <button type="button" 
                            class="am-btn am-btn-success am-btn-sm am-radius look_btn"
                             data-item=${JSON.stringify(item)}>详情</button>
                        </td>
                    </tr>`
  })
  $('.week_detail table tbody').html(weekHtml)
  $('#weekName').html(weekKey)
})
//选择周
$('.week_content').on('click', '.look_btn', function () {
  if(weekIndex>0&&$('#testCourse').length>0){
    var index=layer.confirm('只能查看第一周的课程，如需查看其他课程，请前往公众号购买。',{title:'友情提示'},function () {
      layer.close(index)
    })
    return false
  }
  $('.am-dimmer').fadeIn()
  $('.new_add_modal').show()
  //视频
  var dataItem = JSON.parse($(this).attr('data-item'))
  console.log(dataItem)
  $('#courseTitle').html(dataItem.title) //设置课程标题
  //table
  $('#modalTable').html(`<tr>
                    <td class="cur">水平</td>
                    <td>${dataItem.level}</td>
                    <td class="cur">难度</td>
                    <td>${dataItem.difficulty}</td>
                    <td class="cur">时长</td>
                    <td>${dataItem.duration}</td>
                    <td class="cur">人数</td>
                    <td>${dataItem.people_num}人</td>
                </tr>
                <tr>
                    <td class="cur">上肢力量</td>
                    <td colspan="3"> ${starFun(dataItem.sz)}</td>
                    <td class="cur">平衡性</td>
                    <td colspan="3"> ${starFun(dataItem.ph)}</td>
                </tr>
                <tr>
                    <td class="cur">下肢力量</td>
                    <td colspan="3"> ${starFun(dataItem.xz)}</td>
                    <td class="cur">协调性</td>
                    <td colspan="3"> ${starFun(dataItem.xt)}</td>
                </tr>
                <tr>
                    <td class="cur">柔韧性</td>
                    <td colspan="3"> ${starFun(dataItem.rr)}</td>
                    <td class="cur">灵敏性</td>
                    <td colspan="3"> ${starFun(dataItem.lm)}</td>
                </tr>
`)
  //切换条
  $('[data-info="course_video"]').attr('data-value', dataItem.course_video) //课程讲解
  $('[data-info="rhythm_video"]').attr('data-value', dataItem.rhythm_video)// 律动课程
  $('[data-info="teachingt_img"]').attr('data-value', dataItem.teachingt_img)// 教案
  $('[data-info="game_video"]').attr('data-value', dataItem.game_video) // 游戏课程
  $('[data-info="book_video"]').attr('data-value', dataItem.book_video) // 绘本课程
  // 设置默认
  $('[data-info="rhythm_video"]').addClass('cur').siblings('span').removeClass('cur')
  // 判断按钮显示隐藏
  $('.switch_bar span').each(function (i, d) {
    if ($(d).attr('data-value').trim() === '') {
      $(d).hide()
    } else {
      $(d).show()
    }
  })
  //初始设置
  var initInfo = $('.switch_bar span.cur').attr('data-info')
  var initValue = $('.switch_bar span.cur').attr('data-value')
  showContentFun(initInfo, initValue)
})
var Player = null; //视频 对象
function showContentFun (info, v) {
  if (v.trim() == '') {
    $('.source_container').html('<p class="no_data">暂无内容</p>')
    return;
  }
  if (info === 'teachingt_img') {
    $('.source_container').html(`<div class="img_content" id="printContent"><img src="${v}" alt=""></div> `)
    //  设置下载链接
    $('#downloadBtn').attr('data-src', v)
    $('.btn_content').show()
  } else {  //视频展示
    Player && Player.dispose();
    $('.source_container').html(`
        <div class="video_content ">
            <video id="videoID${v}" preload="auto" playToggle="false"playsinline webkit-playsinline x5-playsinline></video>
        </div>
    `)
    Player = TCPlayer("videoID" + v, { // player-container-id 为播放器容器ID，必须与html中一致
      fileID: v, // 请传入需要播放的视频fileID 必须
      appID: "1256051987", // 请传入点播账号的子应用appID 必须
      autoplay: false,//是否自动播放
      width: $('.video_content').width(),
    });
    $('.btn_content').hide()
  }
}
//关闭按钮
$('.am-close').click(function (e) {
  e.preventDefault()
  $(this).parents('.am-modal').hide()
  $('.am-dimmer').fadeOut()
  $('.source_container').html('')
  try {
    Player.dispose()
    Player = null
  } catch (err) {
  }
})
//关闭小弹框
$('body').on('click', function (e) {
  var notClose = $(e.target).parents().hasClass('week_content') ||
    $(e.target).parents().hasClass('am-modal') ||
    $(e.target).hasClass('am-modal')
  if (!notClose) {
    $('.table_detail').hide()
  }
})
//下载
$('body').on('click', '#downloadBtn', function (e) {
  e.preventDefault()
  window.open($(this).attr('data-src'))
})
// 打印
$('body').on('click', '#printBtn', function (e) {
  print()
})
function print () {
  var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
  if (userAgent.indexOf("trident") > -1) {
    alert("请使用google或者360浏览器打印");
    return false;
  } else if (userAgent.indexOf('msie') > -1) {
    var onlyChoseAlert = simpleAlert({
      "content": "请使用Google或者360浏览器打印",
      "buttons": {
        "确定": function () {
          onlyChoseAlert.close();
        }
      }
    })
    alert("请使用google或者360浏览器打印");
    return false;
  } else {//其它浏览器使用lodop
    var oldstr = document.body.innerHTML;
    var headstr = "<html><head><title></title></head><body>";
    var footstr = "</body></html>";
    //执行隐藏打印区域不需要打印的内容
    // document.getElementById("otherpho").style.display="none";
    var printData = document.getElementById("printContent").innerHTML; //获得 div 里的所有 html 数据
    var wind = window.open("", "newwin",
      "toolbar=no,scrollbars=yes,menubar=no");
    wind.document.body.innerHTML = headstr + printData + footstr;
    wind.print();
    //打印结束后，放开隐藏内容
    // document.getElementById("otherpho").style.display="block";
    wind.close();
    window.document.body.innerHTML = oldstr;
    location.reload()
  }
}